import json


def load_data(file_path):
    with open(file_path, 'r') as f:
        data = json.load(f)
    return data


def process_fractals(data):
    last_fractal_type = None
    last_fractal_index = None
    i = 0

    while i < len(data):
        if data[i]['top_fractal']:
            if last_fractal_type == 'top':
                # Compare and keep the highest top fractal
                if data[i]['high'] > data[last_fractal_index]['high']:
                    data[last_fractal_index]['top_fractal'] = False
                    last_fractal_index = i
                else:
                    data[i]['top_fractal'] = False
            else:
                last_fractal_type = 'top'
                last_fractal_index = i

        elif data[i]['bottom_fractal']:
            if last_fractal_type == 'bottom':
                # Compare and keep the lowest bottom fractal
                if data[i]['low'] < data[last_fractal_index]['low']:
                    data[last_fractal_index]['bottom_fractal'] = False
                    last_fractal_index = i
                else:
                    data[i]['bottom_fractal'] = False
            else:
                last_fractal_type = 'bottom'
                last_fractal_index = i

        # Reset the last fractal if we encounter the opposite fractal type
        if last_fractal_type == 'top' and data[i]['bottom_fractal']:
            last_fractal_type = 'bottom'
            last_fractal_index = i
        elif last_fractal_type == 'bottom' and data[i]['top_fractal']:
            last_fractal_type = 'top'
            last_fractal_index = i

        i += 1

    return data


def save_data(data, output_file):
    with open(output_file, 'w') as f:
        json.dump(data, f, indent=4)


if __name__ == "__main__":
    input_file = '../static/processed_bnb_usdt_klines.json'
    output_file = '../static/final_processed_bnb_usdt_klines.json'

    kline_data = load_data(input_file)
    processed_fractals = process_fractals(kline_data)
    save_data(processed_fractals, output_file)

    print(f"Final processed fractals have been saved to {output_file}")
